
layui.use(['jquery', 'table', "echarts", "carousel", "table"], function(){
    var $ = layui.$, form = layui.form,
        echarts = layui.echarts, admin = layui.admin,
        view = layui.view, table = layui.table;
    var host = "";
    var classInfoIndexList = [];    // 课程索引列表
    var classInfoData;              // 存放课程信息
    var radioIdMap = {};            // radio id记录
    var selClassInfoIndexList = [];
    var radioId = 0;
    var courseType = $('#courseType')[0].innerText.trim();
    var tableln;
    renderCourseList();
    // 获取学生的专业、年级信息
    function renderCourseList() {
        var load = layer.load(2);
        $.ajax({
            url:  host + "/jw/course/" + courseType,
            headers:{'Cookie': layui.data('itstudio')['Cookie']},
            dataType: 'JSON',
            complete: function (result) {
                debugger;
                result = result.responseJSON;
                if (result['status'] === 200) {
                    classInfoData = result['data'];
                    var listStr = JSON.stringify(layui.sessionData("stuCourse"));
                    if (listStr !== "{}") {
                        var stuCourse = JSON.parse(layui.sessionData("stuCourse")['list']);
                        afterGetStuCourse(stuCourse);
                        layer.close(load);
                    }else {
                        $.ajax({
                            url:  host + "/jw/stu/timetable",
                            headers:{'Cookie': layui.data('itstudio')['Cookie']},
                            dataType: "JSON",
                            complete: function (result) {
                                result = result.responseJSON;
                                if (result["status"] === 200) {
                                    layui.sessionData("stuCourse", {
                                        key: "list",
                                        value: JSON.stringify(result["data"]["courseList"])
                                    });
                                    afterGetStuCourse(result["data"]["courseList"]);
                                    layer.close(load);
                                }else {
                                    layer.close(load);
                                    layer.msg(result['message'])
                                }
                            }});
                    }
                }else {
                    layer.close(load);
                    layer.msg(result['message'])
                }
            }
        });
    }

    function afterGetStuCourse(stuCourse) {
        var conflictList = getConflictList(stuCourse, classInfoData);
        var newClassData = [];
        for(var i = 0; i < classInfoData.length; i++) {
            if (!conflictList[i]) {
                newClassData.push(classInfoData[i])
            }
        }
        classInfoData = newClassData;
        renderTable(classInfoData);
        renderRadio();
        $('#refreshBtn').hide();
    }

    // 请求成功后
    function renderRadio() {
        // 清理工作
        $('#campus-radio').empty();
        $('#class-radio').empty();
        $('#teacher-radio').empty();
        $('#time-radio').empty();
        radioIdMap = {};
        radioId = 0;

        // 添加数据
        var data = [];
        if (selClassInfoIndexList.length === 0) {
            data = classInfoData;
        }else {
            for (var i = 0; i < selClassInfoIndexList.length; i++) {
                data.push(classInfoData[selClassInfoIndexList[i]]);
            }
        }
        var campusSet = new Set();
        var classNameSet = new Set();
        var teacherSet = new Set();
        var timeSet = new Set();

        for(var index in data) {
            var oneClass = data[index];
            var campus = oneClass.campus;
            campusSet.add(campus);
            var className = oneClass.className;
            classNameSet.add(className);
            var teacher = oneClass.teachers.toString();
            teacherSet.add(teacher);
            var timeList = [];
            oneClass.time.forEach(function (value) {
                timeList.push(value.description);
            });
            var time = timeList.toString();
            timeSet.add(time);
            classInfoIndexList.push(index);
        }
        // 排序
        timeSet = new Set(Array.from(timeSet).sort(sortText));
        teacherSet = new Set(Array.from(teacherSet).sort(sortText));
        classNameSet = new Set(Array.from(classNameSet).sort(sortText));
        for (campus of campusSet) {
            addRadio("campus-radio", "campus", campus, campusSet.size === 1);
        }
        for (className of classNameSet) {
            addRadio("class-radio", "className", className, classNameSet.size === 1);
        }
        for (var teacher of teacherSet) {
            addRadio("teacher-radio", "teacher", teacher, teacherSet.size === 1);
        }
        for (var time of timeSet) {
            addRadio("time-radio", "time", time, timeSet.size === 1);
        }
        form.render();
        // 人数显示
        if (selClassInfoIndexList.length === 0) {
            drawPersonNum(classInfoIndexList);
        }else {
            drawPersonNum(selClassInfoIndexList);
        }
    }

    // 数组变为字符串
    function strs2Str(strs) {
        var s = "";
        for (var i = 0; i < strs.length; i++) {
            var str = strs[i];
            if(i < strs.length - 1) {
                s += (str + ",")
            } else {
                s += str
            }
        }
        return s;
    }

    function list2Str(list, key) {
        var str = "";
        var set = new Set();
        for(var i = 0; i < list.length; i++) {
            set.add(list[i][key])
        }
        set.forEach(function (data) {
            str += data + " "
        });
        return str;
    }

    function addRadio(id, name, value, checked) {
        radioIdMap[value] = "radio-" + radioId++;
        var title = value;
        if (title.length > 23) title = title.substring(0, 21) + "..";
        var html = "<input type='radio' lay-filter='filter' name=" + name + " value='" + value + "' title='" + title + "' id='" + radioIdMap[value]  + "'";
        if (checked){
            html += " checked>";
        }else {
            html += ">";
        }
        $('#' + id).append(html);
    }

    // 人数画图
    function drawPersonNum(classinfoIndexs) {
        var classlist = [];
        var limitNums = [];
        var nowNums = [];
        var determineNums = [];
        classinfoIndexs.forEach(function (index) {
            var timeList = [];
            classInfoData[index].time.forEach(function (value) {
                timeList.push(value.description);
            });
            classlist.push(classInfoData[index].className + "." + classInfoData[index].teachers.toString() + "--" + timeList.toString())
            limitNums.push(classInfoData[index].limitNum);
            nowNums.push(classInfoData[index].nowNum);
            determineNums.push(classInfoData[index].determineNum);
        });

        // 根据数量和宽度判断变成折线图还是柱状图
        var width = window.screen.availWidth;
        var type = "line";
        if (classinfoIndexs.length <= 8 && width > 800) {
            type = "bar";
        }


        // 是否有滑动条,以及显示多少数据
        var len = 100;
        var slide = false;
        if (classinfoIndexs.length >= 20 || width < 1000) {
            slide = true;
            var num = parseInt(width / 100 * 1.2);
            len = parseInt(num / classinfoIndexs.length * 100);
        }

        if (classinfoIndexs.length === 1) {
            type = "bar";
            slide = false;
        }
        var personData = {
            title: {
                text: '专业课人数',
                textAlign: "auto",
                textStyle: {
                    fontSize: 14
                }
            },
            tooltip: {
                trigger: "axis",
                formatter: function(data)
                {
                    var teacher = data[0].name.split(".")[1].split("--")[0] + "</br>";

                    var timeStart = data[0].name.indexOf("--");
                    var time = data[0].name.substr(timeStart + 2);
                    var timeList = time.split(",");
                    var timeDescription = "";
                    timeList.forEach(function (time) {
                        timeDescription += time + "</br>";
                    });

                    var personDescription = "";
                    data.forEach(function (classData) {
                        personDescription += classData.seriesName + "：" + classData.data + "</br>"
                    });

                    return teacher + timeDescription + personDescription;
                }
            },
            legend: {
                type: "scroll",
                data: ["限选", "已选", "确定"]
            },
            xAxis: [{
                type: "category",
                boundaryGap: true,
                axisLabel : {
                    interval:0,
                    rotate:20,
                    formatter : function(params){
                        var index = params.indexOf("--");
                        var str = params.substr(0, index);
                        if (str.length > 11) {
                            return str.substr(0, 10) + ".."
                        }
                        return str;
                    }

                },
                data: classlist
            }],
            yAxis: [{
                type: "value"
            }],
            series: [{
                name: "限选",
                type: type,
                barMaxWidth:30,
                smooth: !0,
                itemStyle: {
                    normal: {
                        areaStyle: {
                            type: "default"
                        }
                    }
                },
                data: limitNums
            }, {
                name: "已选",
                type: type,
                barMaxWidth:30,
                smooth: !0,
                itemStyle: {
                    normal: {
                        areaStyle: {
                            type: "default"
                        }
                    }
                },
                data: nowNums
            },{
                name: "确定",
                type: type,
                barMaxWidth:30,
                smooth: !0,
                itemStyle: {
                    normal: {
                        areaStyle: {
                            type: "default"
                        }
                    }
                },
                data: determineNums
            }],
            dataZoom:{
                type: 'slider',
                show: slide,
                height:10,//滚动条高度
                start:0,//滚动条开始位置（共100等份）
                end: len//结束位置（共100等份）
            }
        };
        var card= document.getElementById('LAY-index-dataview');
        var myChart = echarts.init(card, layui.echartsTheme);
        myChart.setOption(personData);
        myChart.resize();
    }

    // 监听radio
    form.on('radio(filter)', function(data){
        // 显示重选按钮
        $('#refreshBtn').show();

        var sel_campus = $("input[name='campus']:checked").val();
        var sel_className = $("input[name='className']:checked").val();
        var sel_teacher = $("input[name='teacher']:checked").val();
        var sel_time = $("input[name='time']:checked").val();
        selClassInfoIndexList = [];
        var selClassInfoList = [];
        for (var index in classInfoData) {
            var oneClass = classInfoData[index];
            if (sel_campus == null || sel_campus === oneClass.campus) {
                if (sel_className == null || sel_className === oneClass.className) {
                    if (sel_teacher == null || sel_teacher === oneClass.teachers.toString()) {
                        var timeList = [];
                        oneClass.time.forEach(function (value) {
                            timeList.push(value.description);
                        });
                        if (sel_time == null || sel_time === timeList.toString()) {
                            selClassInfoIndexList.push(index);
                            selClassInfoList.push(classInfoData[index])
                        }
                    }
                }
            }
        }

        renderTable(selClassInfoList);
        renderRadio();
        form.render();
    });

    // 监听确认按钮
    form.on("submit(submit)", function () {
        if ( selClassInfoIndexList.length !== 1) {
            layer.msg("请选择");
            return;
        }
        var data = classInfoData[selClassInfoIndexList[0]];
        admin.popup({
            title: "选课",
            area: ["420px", window.screen.availHeight * 0.9 + "px"],
            id: "LAY-popup-user-elective-confirm",
            success: function(layero, index) {
                data['teacher'] = data['teachers'].toString();
                var remark = "";
                var timeList = data.time;
                layui.each(timeList, function (index, item) {
                    remark += item.description;
                    if(item.classRoom.toString() !== "") {
                        remark += "-" + item.classRoom.toString();
                    }
                    if (item.remark !== "") {
                        remark += "-" + item.remark;
                    }
                    remark += "<br>";
                });
                data['remark'] = remark;
                view(this.id).render("menu/elective/confirmClass", data).done(function () {
                    form.on("submit(LAY-user-back-submit)",function (formData) {
                        layer.close(index);
                        var load = layer.load(2);
                        var field = formData.field;
                        var content = {};
                        content['classCode'] = data.classCode;
                        content['classNum'] = data.classNum;
                        content['coin'] = $('#coinDiv')[0].textContent;
                        content['buy'] = field.hasOwnProperty("buy");
                        content['retake'] = field.hasOwnProperty("retake");
                        content['adjust'] = field.hasOwnProperty("adjust");
                        $.ajax({
                            url:  host + '/jw/stu/course/elective/save',
                            headers:{'Cookie': layui.data('itstudio')['Cookie']},
                            type: 'POST',
                            contentType: 'application/json',
                            data: JSON.stringify(content),
                            dataType: 'json',
                            complete: function (result) {
                                result = result.responseJSON;
                                if (result.status === 200) {
                                    layer.msg("选课成功");
                                    layui.sessionData("stuCourse", null);
                                }else {
                                    layer.msg(result.message);
                                }
                                layer.close(load);
                            }
                        })
                    });
                });
            }
        });
    });

    // 监听重选按钮
    form.on("submit(refresh)", function () {
        selClassInfoIndexList = [];
        renderTable(classInfoData);
        renderRadio();
        // 隐藏按钮
        $('#refreshBtn').hide();
        form.render();
    });

    function transCourseTimeList(courseList) {
        var result = [];
        for (var i = 0; i < courseList.length; i++) {
            var courseTimes = [];
            for (var j = 0; j < courseList[i]["time"].length; j++) {
                courseTimes.push(courseList[i]["time"][j])
            }
            result.push(courseTimes)
        }
        return result;
    }
    function checkTimeConflict(courseTime, stuCourseTimeList) {
        for (var i = 0; i < stuCourseTimeList.length; i++) {
            var weeks = courseTime["weeks"];
            for (var j = 0; j < weeks.length; j++) {
                var anotherWeek = stuCourseTimeList[i]["weeks"];
                if (anotherWeek.includes(weeks[j])) {
                    if (courseTime["day"] === stuCourseTimeList[i]["day"]) {
                        var lesson = courseTime["lesson"];
                        for (var k = 0; k < lesson.length; k++) {
                            if (stuCourseTimeList[i]["lesson"].includes(lesson[k])) {
                                return true;
                            }
                        }
                    }
                }
            }
        }
        return false;
    }
    function getTimeConflict(stuCourseList, courseList) {
        var stuCourseTimeList = [];
        for (var i = 0; i < stuCourseList.length; i++) {
            for (var j = 0; j < stuCourseList[i]["time"].length; j++) {
                stuCourseTimeList.push(stuCourseList[i]["time"][j])
            }
        }
        var courseTimeList = transCourseTimeList(courseList);
        var result = [];
        for (i = 0; i < courseTimeList.length; i++) {
            var add = false;
            for (j = 0; j < courseTimeList[i].length; j++) {
                var conflict = checkTimeConflict(courseTimeList[i][j], stuCourseTimeList);
                if (conflict) {
                    result.push(conflict);
                    add = true;
                    break;
                }
            }
            if (!add) result.push(false)
        }
        return result;
    }
    function getPersonNumConflict(classInfos) {
        var personNumConflict = [];
        for (var i = 0; i< classInfos.length; i++) {
            personNumConflict.push(classInfos[i]["limitNum"] <= classInfos[i]["determineNum"])
        }
        return personNumConflict;
    }
    function getConflictList(stuCourseList, courseList) {
        var timeConflict = getTimeConflict(stuCourseList, courseList);
        var personNumConflict = getPersonNumConflict(courseList);
        var conflictList = [];
        for (var i = 0; i <  courseList.length; i++) {
            conflictList.push(timeConflict[i] || personNumConflict[i])
        }
        return conflictList;
    }

    function renderTable(classInfoDataList) {
        if (tableln === undefined) {
            tableln = table.render({
                elem: '#test-table-page'
                ,cols:[[
                    {field:'className', width:200, title:'课程', align:'left'}
                    ,{field:'teacher',  width:200, title:'教师', align:'left', templet: function (d) { return strs2Str(d['teachers']) }}
                    ,{field:'time', width:320, title:'时间', templet: function (d) {return list2Str(d.time, "description")}}
                    ,{field:'credit', width:60, title:'学分'}
                    ,{field: 'remark', minWidth:200, title:'备注', templet: function (d) { return list2Str(d.time, "remark")}}
                ]]
                ,data: classInfoDataList
                ,limit: classInfoDataList.length
            });
        }else {
            tableln.reload({
                data: classInfoDataList
                ,limit: classInfoDataList.length
            })
        }
    }

    // 汉字排序
    function replaceCNNumberStr(v){
        return v.replace(/\u4e00/,'1').replace(/\u4e8c/,'2').replace(/\u4e09/,'3').replace(/\u56db/,'4').replace(/\u4e94/,'5').replace(/\u516d/,'6').replace(/\u4e03/,'7').replace(/\u516b/,'8').replace(/\u4e5d/,'9').replace(/\u5341/,'10');
    }
    function sortText(a,b) {
        a = replaceCNNumberStr(a);
        b = replaceCNNumberStr(b);
        return ((a < b) ? -1 : ((a > b) ? 1 : 0));
    }
});
